<template>
  <div style="padding: 20px;">
    <div class="topLocation">货物信息管理 / 分类管理</div>
    <div class="topTool">
      <div class="group">分类名：</div>
      <el-input v-model="searchName" placeholder="请输入分类名" style="margin-right: 50px;"></el-input>
      <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      <el-button type="success" :icon="Plus" @click="handleAdd">添加</el-button>
      <el-button type="danger" :icon="Delete" @click="handleDelList" v-if="multipleSelection.length > 0">删除选中分类</el-button>
    </div>
    <el-table
        :data="categoryData"
        :header-cell-style="{ background: '#f6f9fa'}"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column prop="id" label="ID" sortable></el-table-column>
      <el-table-column prop="name" label="分类名"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 添加分类的对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="50%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="分类名">
          <el-input v-model="form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogOk">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus, Search } from "@element-plus/icons-vue";

const categoryData = ref([]); // 分类数据
const currentPage = ref(1); // 当前页数
const pageSize = ref(5); // 每页显示条数
const total = ref(0); // 总记录数
const searchName = ref(''); // 分类名搜索关键字

// 获取数据
const getData = () => {
  axios.get('http://localhost:8080/category/findByPage', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchName.value
    }
  }).then(response => {
    categoryData.value = response.data.data.records;
    total.value = response.data.data.total;
  }).catch(error => {
    console.error(error);
  });
};

onMounted(() => {
  getData();
});

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getData();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  getData();
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
      `您确定要删除分类【${row.name}】的记录吗?`,
      '危险操作'
  ).then(() => {
    delCategory(row.id);
    ElMessage({
      type: 'success',
      message: '删除成功!',
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!',
    });
  });
};

const delCategory = (categoryId) => {
  axios.delete(`http://localhost:8080/category/${categoryId}`)
      .then(() => {
        getData();
      })
      .catch((error) => {
        console.error(error);
      });
};

const handleSearch = () => {
  // 判断搜索框是否为空
  const searchQuery = searchName.value.trim();

  if (searchQuery === '') {
    // 如果为空，调用获取所有分类的接口
    axios.get('http://localhost:8080/category')
        .then(response => {
          categoryData.value = response.data.data; // 返回所有分类数据
        })
        .catch(error => {
          console.error(error);
          ElMessage.error('获取所有分类失败');
        });
  } else {
    // 如果不为空，调用模糊查询接口
    axios.get(`http://localhost:8080/category/findByName/${searchQuery}`)
        .then(response => {
          categoryData.value = response.data.data; // 返回模糊查询结果
        })
        .catch(error => {
          console.error(error);
          ElMessage.error('查询失败');
        });
  }
};

const handleSortChange = (sortData) => {
  const { prop, order } = sortData;
  categoryData.value = categoryData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });
};

let multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val.map(item => item.id);
};

const handleDelList = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的分类！');
    return;
  }
  ElMessageBox.confirm(
      "您确定要删除选中的分类？",
      '危险操作'
  ).then(() => {
    multipleSelection.value.forEach((id) => {
      delCategory(id);
    });
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!'
    });
  });
};

const dialogFormVisible = ref(false);
const dialogTitle = ref('添加分类');
const form = ref({
  id: null,
  name: '',
  remark: '' // 分类备注
});

const handleAdd = () => {
  dialogTitle.value = '添加分类';
  form.value = { ...form.value, id: null, name: '', remark: '' };
  dialogFormVisible.value = true;
};

const handleEdit = (row) => {
  dialogTitle.value = '编辑分类';
  form.value = { ...row };
  dialogFormVisible.value = true;
};

const dialogOk = () => {
  // 表单验证，确保所有字段都有值
  if (!form.value.name || !form.value.remark) {
    ElMessage.error('所有字段都必须填写');
    return; // 阻止后续操作
  }

  // 如果是添加分类操作
  if (dialogTitle.value === '添加分类') {
    // 类别名称重复检查
    axios.post('http://localhost:8080/category/checkCategory', { name: form.value.name })
        .then(response => {
          // 检查类别名称是否存在
          if (response.data.data.exists === true) {
            ElMessage.error('类别名称已存在，请选择其他名称');
            return; // 阻止继续执行
          }

          // 类别名称不存在，继续添加分类
          axios.post('http://localhost:8080/category', form.value)
              .then(() => {
                dialogFormVisible.value = false; // 关闭弹窗
                getData(); // 刷新数据
                ElMessage.success('添加成功!'); // 提示成功
              })
              .catch((error) => {
                console.error(error);
                ElMessage.error('添加分类失败，请稍后再试');
              });
        })
        .catch((error) => {
          console.error(error);
          ElMessage.error('类别名称检查失败，请稍后再试');
        });
  } else { // 编辑分类
    axios.put(`http://localhost:8080/category/${form.value.id}`, form.value)
        .then(() => {
          dialogFormVisible.value = false; // 关闭弹窗
          getData(); // 刷新数据
          ElMessage.success('编辑成功!'); // 提示成功
        })
        .catch((error) => {
          console.error(error);
          ElMessage.error('编辑失败，请稍后再试');
        });
  }
};

</script>

<style scoped>
.topLocation {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 文字颜色为黑色 */
  padding: 10px;
  border-bottom: 2px solid #000; /* 底部边框，黑色 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
  margin-bottom: 20px; /* 增加距离 */
}

.topTool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.group {
  white-space: nowrap; /* 防止文字换行 */
  font-size: 14px;     /* 设置字体大小为 14px */
}
</style>
